<?php

namespace App\Console\Commands\Common;

use App\Models\Common\CityTerritorialBoundaryModel;
use App\Remote\AMap\AMapRemote;
use Illuminate\Console\Command;

class GenerateCityTerritorialBoundary extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'common:generateCityTerritorialBoundary';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '生成高德地图城市边界表';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        ini_set('memory_limit', '1024M');
        $cityTerritorialBoundaryCount = CityTerritorialBoundaryModel::query()
//                                                                    ->where("level", CityTerritorialBoundaryModel::LEVEL_CITY)
                                                                    ->count();
        if ($cityTerritorialBoundaryCount == 0) {
            //初始化数据
            $this->info("初始化数据");
            $cityResponse = AMapRemote::district(3);
            $this->build($cityResponse["districts"]);
        }

        //获取城市边界信息
        CityTerritorialBoundaryModel::query()->where("polyline", "=", null)->get()->each(function (
            CityTerritorialBoundaryModel $territorialBoundaryModel
        ) {
            $this->info("更新边界 {$territorialBoundaryModel->name}");
            try {
                $polylineResponse                   = AMapRemote::district(0, "all", $territorialBoundaryModel->adcode);
                $territorialBoundaryModel->polyline = $polylineResponse["districts"][0]["polyline"];
                $territorialBoundaryModel->save();
                $this->info("更新边界 {$territorialBoundaryModel->name} 成功");
            } catch (\Exception $exception) {
                $this->error("更新边界 {$territorialBoundaryModel->name} 失败");
            }
        });

        return parent::SUCCESS;
    }

    public function build(array $districts, string $pAdcode = "")
    {
        foreach ($districts as $district) {
            list($centerLongitude, $centerLatitude) = explode(",", $district["center"]);
            $insertData = array_merge([
                "pAdcode"         => $pAdcode,
                "adcode"          => $district["adcode"],
                "name"            => $district["name"],
                "centerLongitude" => $centerLongitude,
                "centerLatitude"  => $centerLatitude,
                "level"           => $district["level"],
                "citycode"        => empty($district["citycode"]) ? "" : $district["citycode"]
            ], ["createdAt" => time()]);
            CityTerritorialBoundaryModel::query()->insert($insertData);
            $this->info(json_encode($insertData));

            if ($district["districts"]) {
                $this->build($district["districts"], $district["adcode"]);
            }
        }
    }
}
